import { dbQuery } from "../util/db";
import { KeyValue } from "../util/param";

export const AddContent = (query: KeyValue) => {
  return dbQuery(
    `INSERT INTO content(
      title,
      author,
      tip,
      fileUrl,
      imgUrl,
      original,
      tag,
      createTime,
      openTimes,
      isnote,
      demoUrl
      ) VALUES(
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?
        )`,
    [
      query.title,
      query.author,
      query.tip,
      query.fileUrl,
      query.imgUrl,
      query.original,
      query.tag,
      new Date().getTime(),
      0,
      query.isnote,
      query.demoUrl,
    ]
  );
};

export const SelectOneContent = (query: KeyValue) => {
  const { id } = query;
  return dbQuery(`SELECT * FROM content WHERE id=${id}`);
};

export const SelectAllContent = () => {
  return dbQuery(`SELECT * FROM content ORDER BY createTime DESC`);
};

export const SelectTopContent = (query: KeyValue) => {
  const { top } = query;
  return dbQuery(`
  SELECT
    id 
  FROM
    content 
  ORDER BY
	  openTimes DESC 
	LIMIT 3
   `);
};

export const DeleteContent = (query: KeyValue) => {
  return dbQuery(`DELETE FROM content WHERE id = ?`, [query.id]);
};

export const UpdateContent = (query: KeyValue) => {
  const {
    title,
    author,
    tip,
    fileUrl,
    imgUrl,
    original,
    tag,
    id,
    isnote,
    demoUrl,
  } = query;
  return dbQuery(
    `
    UPDATE content 
    SET 
      title = ?,
      author = ?,
      tip = ?,
      fileUrl = ?,
      imgUrl = ?,
      original = ?,
      tag = ?,
      isnote = ?,
      demoUrl = ?
    WHERE
      id = ?
    `,
    [title, author, tip, fileUrl, imgUrl, original, tag, isnote, demoUrl, id]
  );
};

export const UpdateContentOpenTimes = (query: KeyValue) => {
  const { id } = query;
  return dbQuery(
    `
  UPDATE
    content 
  SET  
    openTimes = openTimes + 1  
  WHERE
    id = ?
  `,
    [id]
  );
};
